package com.freshman_registration.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.freshman_registration.mapper.AdminMapper;
import com.freshman_registration.pojo.Admins;
import com.freshman_registration.service.AdminService;
import com.freshman_registration.util.Result;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    //判断工号是否存在
    @Override
    public Result<Admins> queryAdminByWorkNo(String workNo) {
        Admins admin = adminMapper.queryAdminByWorkNo(workNo);
        if (admin != null) {
            return Result.success(admin);  // 查询到数据返回成功结果
        }
        return Result.fail("未查询到该工号的管理员信息");  // 明确提示工号相关
    }
//    添加管理员信息
    @Override
    public Result<?> insertAdmin(Admins admin) {
        Admins existingAdmin = adminMapper.queryAdminByWorkNo(admin.getWorkNo());
        if (existingAdmin == null) {
            admin.setCreateTime(new Date());
            // 密码加密
            admin.setPassword(SecureUtil.md5(admin.getPassword()));

            int insert = adminMapper.insertAdmin(admin);
            if (insert > 0) {
                return Result.success("添加成功");
            }
            return Result.fail("添加失败");
        }
        return Result.fail("该工号已被注册");
    }

    //根据id修改
    @Override
    public Result<?> updateAdmin(Admins admin) {

        if(admin.getPassword()!=null && !"".equals(admin.getPassword().trim()))
        {
            admin.setPassword(SecureUtil.md5(admin.getPassword()));
        }
        admin.setUpdateTime(new Date());
        int update = adminMapper.updateAdmin(admin);
        if (update > 0) {
            return Result.success("修改成功");
        }
        return Result.fail("修改失败（可能管理员ID不存在或数据无变化");
    }

    //根据id删除管理员信息
    @Override
    public Result<?> deleteAdmin(Integer id) {
        int delete = adminMapper.deleteAdmin(id);
        if (delete > 0) {
            return Result.success("删除成功");
        }
        return Result.fail("管理员id不存在，删除失败");
    }
    //分页查询所有管理员信息
    @Override
    public Page queryAllAdmins(Integer currentPage, Integer pageSize) {
        Page<Admins> page = PageHelper.startPage(currentPage, pageSize);
        List<Admins> admins = adminMapper.queryAllAdmins();
        return page;
    }
    //管理员登录
    @Override
    public Result<?> login(String workNo, String password) {
       Admins admin = adminMapper.login(workNo,new String(SecureUtil.md5(password)));
       return admin == null ? Result.fail("账号或密码错误") : Result.success(admin);
    }

//导出excel
    @Override
    public void exportExcel(HttpServletResponse response) {
        List<Admins> admins = adminMapper.queryAllAdmins(); // 注意方法名小写
        try (ServletOutputStream os = response.getOutputStream();
             ExcelWriter writer = ExcelUtil.getWriter(true)) { // true 表示 .xlsx
            writer.write(admins, true);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("管理员信息表", StandardCharsets.UTF_8.name());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            writer.flush(os, true);
        } catch (IOException e) {
            log.error("导出Excel失败", e);
        }
    }

    //导入excel
    @Override
    public void importTemplate(HttpServletResponse response) throws IOException {
        //1.创建ExcelWriter对象
        ExcelWriter writer = ExcelUtil.getWriter();
        //2.设置导入模板字段
        Map<String, Object> row = new LinkedHashMap<>();
        row.put("id", "自动递增（无需填写）");
        row.put("username", "张三（示例用户名，必填）");
        row.put("password", "123456（示例密码，至少6位，必填）");
        row.put("phone", "13928508520（示例手机号，必填）");
        row.put("photo", "头像路径（可选，如：/profile/avatar.png）");
        row.put("create_time", "2025-09-19（创建日期，格式：yyyy-MM-dd，必填）");
        row.put("status", "1（状态：1=启用，0=禁用，必填）");
        row.put("update_time", "2025-09-19（更新日期，格式：yyyy-MM-dd，可选）");
        row.put("department", "研发部（所属部门，必填）");
        row.put("work_no", "1001（工号，必填）");
        List<Map<String, Object>> users = CollUtil.newArrayList(row);
        //3.将查询结果写入Excel
        writer.write(users, true);
        //4.设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户导入模板", "UTF-8");
        // 5.设置响应头信息
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        //获取输出流对象
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        //关闭流对象
        writer.close();
        IoUtil.close(out);
    }

    //根据状态或用户名分页
    @Override
    public PageInfo<Admins> queryAdmins(Integer status, String username, Integer currentPage, Integer pageSize) {
        // 1. 打印参数（确认currentPage和pageSize有值，不再是空）
        log.info("查询参数：status={}, username={}, currentPage={}, pageSize={}",
                status, username, currentPage, pageSize);

        // 2. 设置分页（PageHelper会自动拦截后续的查询SQL，添加LIMIT分页）
        PageHelper.startPage(currentPage, pageSize);

        // 3. 执行查询（此时返回的List已被PageHelper处理为分页数据）
        List<Admins> adminList = adminMapper.queryAdmins(status, username);

        // 4. 封装为PageInfo（包含总条数、总页数等分页信息，方便前端使用）
        PageInfo<Admins> pageInfo = new PageInfo<>(adminList);
        return pageInfo;
    }


    //根据id批量删除
    @Override
    public Result<?> deleteBatch(List<Integer> ids) {
        int result = adminMapper.deleteBatch(ids);
        if (result > 0) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }
//状态按钮更新
    @Override
    public Result<Integer> updateStatus(Integer id, String status) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            return Result.fail("用户 ID 非法");
        }
        if (status == null || status.trim().isEmpty()) {
            return Result.fail("状态值不能为空");
        }

        // 2. 落库
        int rows = adminMapper.updateStatus(id, status);
        if (rows == 0) {
            return Result.fail("用户不存在或状态已相同");
        }

        // 3. 返回受影响行数
        return Result.success(rows);
    }


    //修改密码
    @Override
    public Result<?> updatePassword(Integer id, String password) {
        if (id == null || id <= 0) {
            return Result.fail("用户 ID 非法");
        }
        if (password == null || password.trim().isEmpty()) {
            return Result.fail("密码不能为空");
        }

        // 对传入的密码进行MD5加密（注意：MD5安全性较低，建议使用BCrypt）
        String encryptedPassword = SecureUtil.md5(password.trim());

        // 落库（存储加密后的密码）
        int rows = adminMapper.updatePassword(id, encryptedPassword);
        if (rows == 0) {
            return Result.fail("用户不存在");
        }

        return Result.success(rows);
    }
}
